package com.isunland.managesystem.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.utils.LogUtil;

public class NewTemproryPlanFragment extends Fragment {

  private WebView mwebView;
  private String url = "";

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.plan_temp);
    url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_WORK);
    LogUtil.i("url==" + url);
    //实例化WebView对象
    mwebView = new WebView(getActivity());

    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

    //设置WebView属性，能够执行Javascript脚本
    mwebView.getSettings().setJavaScriptEnabled(true);
    //设置cookie
    synCookies(getActivity(), url);
    //加载需要显示的网页
    mwebView.loadUrl(url);
    //打开网页时不调用系统浏览器
    mwebView.setWebViewClient(new WebViewClient() {
      @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
      }
    });

    return mwebView;
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;

      default:
        break;
    }

    return super.onOptionsItemSelected(item);
  }

  /**
   * 同步一下cookie
   */
  public static void synCookies(Context context, String url) {
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.removeSessionCookie();//移除
    cookieManager.setCookie(url, RequestManager.getCookie());//cookies是在HttpClient中获得的cookie
    CookieSyncManager.getInstance().sync();
  }
}
